<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-05-15
 * Time: 14:44
 */

namespace app\common\middleware;


class RecordLog
{
    public function handle($request, \Closure $next)
    {
        $response = $next($request);

        $content = isset($request->log_content) ? $request->log_content : '';
        if (empty($content)) {
            return $response;
        }

        $user_name = isset($request->token_data['user_name']) ? $request->token_data['user_name'] : '';
        // 查找当前控制器和方法
        $controller = $request->controller(true);
        $action = $request->action(true);
        if (empty($controller) || empty($action)) {
            $route = $request->rule()->getRoute();
            $route_name = str_replace(['\\','@'],'/',$route);
            $route_name = explode('/',$route_name);
            $controller = ucfirst(isset($route_name[0]) ? $route_name[0] : '');
            $action = ucfirst(isset($route_name[1]) ? $route_name[1] : '');
        }

        write_system_log($content, $user_name, $controller, $action);

        return $response;
    }
}